package impl;

import interfaces.MapPositions;
import candySystemNamespace.Map;
import classes.Constants;
import classes.Coordinate;
import classes.ObservableList;
import classes.Utils;

public class MapImpl extends Map {
	private final String TAG = Constants.TAG + "." + getClass().getSimpleName();

	private ObservableList<Coordinate> freePositions = new ObservableList<Coordinate>();

	private ObservableList<Coordinate> candiesPositions = new ObservableList<Coordinate>();

	public MapImpl(int mapWidth, int mapHeight, int candiesNumber) {
		Utils.logC(TAG, "Creating map object: " + mapWidth + "x" + mapHeight);
		
		// Add all map to free places
		for (int i = 0; i < mapWidth; i++)
			for (int j = 0; j < mapHeight; j++)
				freePositions.add(new Coordinate(i, j));

		// Remove obstacle from free places
		int obstacleWidth = mapWidth / 4;
		int obstacleHeight = mapHeight - 2;
		for (int i = obstacleWidth; i < mapWidth - obstacleWidth; i++)
			for (int j = 1; j <= obstacleHeight; j++)
				freePositions.remove(new Coordinate(i, j));

		// Place candies
		int candiesHeight = mapHeight / 2;
		int candiesWidth = candiesNumber / candiesHeight + (candiesNumber % candiesHeight != 0 ? 1 : 0);
		int count = 0;
		for (int i = 0; i < candiesWidth; i++)
			for (int j = mapHeight / 4; j < candiesHeight + mapHeight / 4; j++) {
				if (count >= candiesNumber)
					break;

				candiesPositions.add(new Coordinate(i, j));
				freePositions.remove(new Coordinate(i, j));
				count++;
			}
	}

	@Override
	protected MapPositions make_mapPositions() {
		return new MapPositions() {
			public ObservableList<Coordinate> getFreePositions() {
				return freePositions;
			}

			public ObservableList<Coordinate> getCandiesPositions() {
				return candiesPositions;
			}
		};
	}

}
